// export const baseUrl = "https://api.pinfengxuan.com";  // 线上
export const baseUrl = "https://www.0563repai.top:9000";  // 预发

const httpInterceptor = {
    // 拦截前触发
    invoke(options: UniApp.RequestOptions) {
        if (!options.url.startsWith('http')) {
            options.url = baseUrl + options.url
        }
        options.timeout = 10000;
        options.header = {
            ...options.header,
            // Isencrypt: 'true',
            // 'Encrypt-Key': rasEncipher(),
            'content-language': 'zh_CN',
        }
        try {
            const token = uni.getStorageSync('token');
            if (token) {
                console.log('options', options);
                options.data = {
                    //@ts-ignore
                    ...(options.data || {}),
                    token,
                }
                // options.body = {
                //     token,
                //     ...options.body,
                // }
            }
        } catch (e) {
            // error
        }
    }
}

uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadfile', httpInterceptor)

interface Data<T> {
    httpCode: string | number,
    errorMessage: string,
    data: T,
    success: boolean,
}

export const http = <T>(options: UniApp.RequestOptions) => {
    console.log('http', options)
    return new Promise<Data<T>>((resolve, reject) => {
        uni.request({
            ...options,
            success(res) {
                console.log('res', options, res)
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    const obj = (res?.data as Data<T> || {});
                    resolve({ ...obj });
                } else {
                    uni.showToast({
                        title: (res.data as Data<T>).errorMessage || '请求错误',
                        icon: 'none',
                    })
                    reject({ ...(res?.data as Data<T> || {}), success: false });
                }
            },
            fail(error) {
                console.log('res_error', options, error)
                uni.showToast({
                    title: '网络错误',
                    icon: 'none',
                })
            }
        })
    })
}